# Prepare MT returns
# Note: clean and rearrange 2020 MT returns
# By Dom Valentino and Chris Kenny
# libs --------------------------------------------------------------------
library(tidyverse) # select(), filter(), mutate(), etc.
library(haven) # read_dta()
library(readxl) # read_excel()

# data --------------------------------------------------------------------
mt_pres <- read_excel('../data/returns_mt/returns_mt_pres.xlsx')
mt_gov <- read_excel('../data/returns_mt/returns_mt_gov.xlsx')
cvap <- read_dta("../data/modified data/county_cvap.dta")
turnout <- read_excel("../data/returns_mt/turnout_mt.xlsx")

# clean
final_mt <- mt_pres %>% left_join(., mt_gov, by = "county") %>% 
  transmute(county = county, 
            fips = NA_real_,
            treat = case_when(
              county %in% c("Beaverhead","Big Horn", "Blaine", "Carter", "Cascade", "Custer", "Daniels", "Dawson", 
                            "Deer Lodge", "Fallon", "Flathead", "Gallatin", "Garfield", "Glacier", "Golden Valley",
                            "Granite", "Hill", "Jefferson", "Judith Basin", "Lake", "Lewis and Clark", "Liberty",
                            "Lincoln", "Madison", "McCone", "Meagher", "Missoula", "Musselshell", "Park", "Phillips", 
                            "Pondera", "Prairie", "Ravalli", "Richland", "Roosevelt", "Rosebud", "Sanders", "Sheridan",
                            "Silver Bow", "Sweet Grass", "Teton", "Toole", "Valley", "Wheatland", "Yellowstone") ~ 1,
              T ~ 0),
            dem_share_pres = as.numeric(dem_pres) / (as.numeric(dem_pres) + as.numeric(rep_pres)), 
            dem_share_sen = NA_real_,
            dem_share_gov = as.numeric(dem_gov) / (as.numeric(dem_gov) + as.numeric(rep_gov)),
            year = 2020) %>% 
  left_join(., turnout, by = "county") %>% # merge turnout
  left_join(., cvap[cvap$year == 2020 & cvap$state == "MT", ], by = "county") %>% 
  mutate(year = year.x, turnout_share = ballots_cast / cvap_approx) %>% 
  select(-year.y, -year.x)

write_csv(final_mt, "../data/analysis/analysis_mt.csv")
